<?php
Cinnamon::loadClass('Session');

/**
 * Cinnamon Visitor Session
 * 
 * Session class that is used on javascript and track modes
 */

class VisitorSession extends Session {
	protected $visitIdentifier;
	
	/**
	 * Default constructor
	 */
	public function __construct() {
		parent::__construct();
		
		// register for events
		Cinnamon::registry('events')->addListener($this);
	}
	
	/**
	 * Returns the (unique) identifier for this visit
	 */	
	public function getVisitIdentifier($site_id) {
		return ( $this->get('site.'. $site_id .'.identifier') );
	}
	
	/**
	 * Listens to preJavascript event
	 */
	public function onPreJavascript($evt) {
		$prefix = 'site.'. $evt->site_id;
		$now = time();
		
		// handle visit identifier
		// each visit has an idle period (15 minutes maximum)
		// in case that the limit is exceeded, we create a new identifier
		$expires = intval($this->get($prefix .'.last.action')) + ( 15 * SECS_PER_MIN );
		if ( !$this->exists($prefix .'.identifier') || ( $now > $expires ) ) {
			$this->set($prefix .'.identifier', md5(uniqid(rand(), true)));
		}
		$this->visitIdentifier = $this->get($prefix .'.identifier');
		
		// update last action
		$this->set($prefix .'.last.action', $now);
	}
	
	/**
	 * Listens to preTrack event
	 */	
	public function onPreTrack($evt) {
		$prefix = 'site.'. $evt->site_id;
		
		// update last actions
		$now = time();
		$this->set($prefix .'.last.action', $now);
	}
}
?>